package com.usbserial.driver;

import android.hardware.usb.UsbDeviceConnection;

import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import com.usbserial.exception.UsbSerialException;

/**
 * Thin adapter around the felHR85 usb-serial driver so we can expose a chipset-agnostic API.
 */
public class FelhrUsbSerialDriver implements UsbSerialDriver {

    private final UsbSerialDevice delegate;
    private UsbDeviceConnection connection;
    private UsbSerialInterface.UsbReadCallback readCallback;

    public FelhrUsbSerialDriver(UsbSerialDevice delegate) {
        this.delegate = delegate;
    }

    @Override
    public void open(UsbDeviceConnection connection) throws UsbSerialException {
        this.connection = connection;
        if (!delegate.open()) {
            throw new UsbSerialException("Unable to open UsbSerialDevice");
        }
    }

    @Override
    public void close() throws UsbSerialException {
        delegate.close();
        if (connection != null) {
            connection.close();
            connection = null;
        }
    }

    @Override
    public void setBaudRate(int baudRate) throws UsbSerialException {
        delegate.setBaudRate(baudRate);
    }

    @Override
    public void setDataBits(int dataBits) throws UsbSerialException {
        delegate.setDataBits(dataBits);
    }

    @Override
    public void setStopBits(int stopBits) throws UsbSerialException {
        delegate.setStopBits(stopBits);
    }

    @Override
    public void setParity(int parity) throws UsbSerialException {
        delegate.setParity(parity);
    }

    @Override
    public void setFlowControl(int mode) throws UsbSerialException {
        delegate.setFlowControl(mode);
    }

    @Override
    public void setDTR(boolean value) throws UsbSerialException {
        delegate.setDTR(value);
    }

    @Override
    public void setRTS(boolean value) throws UsbSerialException {
        delegate.setRTS(value);
    }

    @Override
    public void registerReadCallback(ReadListener listener) throws UsbSerialException {
        readCallback = data -> {
            if (data != null && data.length > 0) {
                listener.onReceived(data);
            }
        };
        delegate.read(readCallback);
    }

    @Override
    public int write(byte[] src, int timeout) throws UsbSerialException {
        return delegate.syncWrite(src, timeout);
    }

    @Override
    public void unregisterReadCallback() throws UsbSerialException {
        readCallback = null;
        delegate.read(null);
    }
}
